package com.example.onlineeducation.utils

import android.text.Editable
import android.text.TextWatcher
import android.widget.EditText
import com.example.onlineeducation.R
import com.yc.jetpacklib.utils.YcResources
import java.util.regex.Pattern

/**
 * SimpleDes:
 * Creator: Flood
 * Date: 2018-12-14
 * UseDes:
 */
open class NumTextWatcher(private val mEditText: EditText) : TextWatcher {
    override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
    override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
        // 清除“数字”和“.”以外的字符
        if(!Pattern.matches(YcResources.getString(R.string.numLimit), s.toString())){
            val str = s.toString().replace(",", "")
        }

    }
    override fun afterTextChanged(s: Editable) {
        val str = s.toString().replace(",", "")

        if (str.isEmpty()) return
        if (".".startsWith(str)) {
            silentSetText("")
            return
        }
        val index = str.indexOf(".")
        if (index > 0 && str.length > index + 3) {
            silentSetText(str.substring(0, str.length - 1))
            mEditText.setSelection(mEditText.text.toString().length)
        }
    }

    //setText时移除文本监听
    private fun silentSetText(s: String?) {
        mEditText.removeTextChangedListener(this)
        mEditText.setText(s)
        mEditText.addTextChangedListener(this)
    }
}